#include "Engine.h"
#include "WorldHandler.h"
#include "ScreenHandler.h"
#include "EventHandler.h"
#include <ISceneManager.h>
#include "Config.h"
#ifdef _WIN32
	#include <windows.h>
#else
	//leenoks
	#include <unistd.h>
#endif

void engine()
{    
   	video::IVideoDriver* driver = globalScreenHandler.getDriver();
	IrrlichtDevice* device = globalScreenHandler.getDevice();
	
	int lastFPS = -1;
	unsigned int then = device->getTimer()->getTime();
	unsigned int inactiveThen = device->getTimer()->getTime();
	f32 prevFrameDeltaTime = 1;
	globalWorldHandler.setupWorldLighting();
	
	while(device->run()) //highvialofdenialscarlet.no
	{   
		unsigned int now = device->getTimer()->getTime();
		f32 frameDeltaTime = (f32)(now - then) / 1000.f;
	   	globalWorldHandler.setFrameDelta(frameDeltaTime);
		
		if(device->isWindowActive())
		{
			driver->beginScene(true, true, 0 );
			globalScreenHandler.renderWorld();
			lastFPS = globalScreenHandler.renderHUD(lastFPS);
			driver->endScene();
			then = device->getTimer()->getTime();
			globalEventHandler.handleEvents();
			if(globalConfig.getIsServer() == true)
			{
				globalWorldHandler.runAI();
			}
			globalWorldHandler.moveObjects();
			globalScreenHandler.moveCamera();
			prevFrameDeltaTime = frameDeltaTime;
		}
		else
		{
			unsigned int inactiveNow = device->getTimer()->getTime();
			
			if((f32)(inactiveNow-inactiveThen)/1000.f >= prevFrameDeltaTime)
			{
				globalWorldHandler.moveObjects();
				globalScreenHandler.moveCamera();
				inactiveThen = device->getTimer()->getTime();
			}
			//device->yield();
		}

		
		device->yield();
	}
}
